//
//  ProductSearchViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 2016/10/28.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "ProductSearchViewController.h"
#import "SearchHistoryView.h"
#import "homeCollectionViewCell.h"
#import "GoodListsModel.h"
#import "ShopDetailsController.h"

@interface ProductSearchViewController ()<UISearchBarDelegate,SearchHistoryViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSString *_filename;
    MBProgressHUD *progressHUD;
    NSUInteger refreshIndex;
    UIImageView *noDrawImage;
    
    //搜索或者选中商品名字
    NSString *_selectStr;
    
    TopPullRefreshAnaimation *gifHeader;
    NSDictionary *_urlDict;
}

@property (nonatomic,strong)UISearchBar *searchBar;
/**
 *  历史记录
 */
@property(nonatomic,strong)NSMutableArray *histArray;

@property(nonatomic,strong)SearchHistoryView *HistoryView;

@property(nonatomic,strong)NSFileManager *filePath;

@property(nonatomic,strong)UITableView *searchView;

@property(nonatomic,strong)UICollectionView *productSearchView;

@property(nonatomic,strong)NSMutableArray *productSearchArray;

@end

@implementation ProductSearchViewController

static NSString * const productReuseIdentifier = @"productReuseIdentifierCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self buildView];
    [self productHistoryList];
    
    refreshIndex = 1;
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    [_searchBar resignFirstResponder];
}

#pragma mark SearchBar代理
//已经结束编辑的回调
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
}

//搜索按钮点击的回调
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"%@",searchBar.text);
    
    _selectStr = searchBar.text;
    //搜索请求
    [self productSearchListDataSearchStr:_selectStr];
    
    [self.histArray addObject:searchBar.text];
    //将记录存入本地
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    _filename = [path stringByAppendingPathComponent:@"productHistoryList.plist"];
    _filePath = [NSFileManager defaultManager];
    [_filePath createFileAtPath:_filename contents:nil attributes:nil];
    
    BOOL stutas = [self.histArray writeToFile:_filename atomically:YES];
    if (stutas) {
        NSLog(@"成功");
    } else {
        NSLog(@"失败");
    }
    _HistoryView.historyArray = self.histArray;
    
}

#pragma mark 历史记录
- (void)productHistoryList
{
    self.HistoryView = [[SearchHistoryView alloc] initWithFrame:CGRectMake(0,0, WIDTH,100 )];
    _HistoryView.delegate = self;
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    _filename = [path stringByAppendingPathComponent:@"productHistoryList.plist"];
    self.histArray = [NSMutableArray arrayWithContentsOfFile:_filename];
    
    _HistoryView.historyArray = self.histArray;
    [self.view addSubview:_HistoryView];
}

//点击
- (void)SearchHistoryDelegateClick:(NSInteger)selectIndex
{
    _selectStr = self.histArray[selectIndex];
    NSLog(@"selectStr%@",_selectStr);
    _searchBar.text = _selectStr;
    //搜索请求
    [self productSearchListDataSearchStr:_selectStr];
}

//删除
- (void)SearchHistorydeleteClick
{
    
    //弹框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定删除全部历史记录?" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okay = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //数组接受本地删除
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
        _filename = [path stringByAppendingPathComponent:@"productHistoryList.plist"];
        self.histArray = [NSMutableArray arrayWithContentsOfFile:_filename];
        
        [self.histArray removeAllObjects];
        //         NSLog(@"???%@",self.histArray);
        
        _HistoryView.isDelete_History = YES;
        _HistoryView.historyArray = self.histArray;
        //删除本地
        NSFileManager *manager=[NSFileManager defaultManager];
        NSString *filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"productHistoryList.plist"];
        if ([manager removeItemAtPath:filepath error:nil]) {
            NSLog(@"文件删除成功");
        }
        
        
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    [alert addAction:okay];
    [alert addAction:cancle];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 上拉刷新
#pragma mark >>>>>>>>刷新
- (void)addPullUpdateData
{
    self.searchView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(productSearchListMoreData)];
    
}

- (void)productSearchListMoreData
{
    refreshIndex ++;
    [self productSearchListDataSearchStr:_selectStr];
    [self.searchView.mj_footer endRefreshing];
}


#pragma mark 商家搜索请求
- (void)productSearchListDataSearchStr:(NSString *)searchStr
{
    //菊花加载
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    
    [self.searchBar resignFirstResponder];
    
    if (refreshIndex == 1) {
        [self.productSearchArray removeAllObjects];
    }
    
    
    if (self.searchView == nil) {
        [self buildCollectionView];
    }
    
    NSString *P = [NSString stringWithFormat:@"%ld",refreshIndex];
    
    NSString *urlStr = @"/api/Business/shopBusinessList";
    NSDictionary *params = @{@"shopId":[NSString stringWithFormat:@"%@", _businessId],
                             @"search_text":searchStr,
                             @"p":P
                             };
    if (_goodsStutas) {
        params = @{@"text":searchStr};
        urlStr = @"/api/goods/lists";
    }
    
    if (_isBussinessProduct) {
        params = @{@"business_id":_businessId,
                   @"text":searchStr
                   };
        urlStr = @"/api/goods/lists";
    }
    
    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:urlStr completeBlock:^(id object) {
        
        NSLog(@"--------%@",object);
        if (JudgeBackDataCode) {
            
            NSDictionary *tempDict = object[@"data"];
            NSArray *arr = [tempDict objectForKey:@"list"];
            _urlDict = tempDict[@"picprex"];
            
            NSLog(@"%@",_urlDict);
            for (NSDictionary *dict in arr) {
                GoodListsModel *goodListsModel = [[GoodListsModel alloc] initWithDictionary:dict error:nil];
                if (goodListsModel) {
                    [self.productSearchArray addObject:goodListsModel];
                    
                }
            }
            
            if (self.searchView == nil) {
                [self buildCollectionView];
            }
            
            
        }else{
            
            refreshIndex = 1;
            [self.searchView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.searchView reloadData];
        [progressHUD hide:YES];
        [progressHUD removeFromSuperViewOnHide];
    }];
    
    
}

#pragma mark 数据源代理
#pragma mark>>>>>>>>>>>数据源
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.productSearchArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    homeCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:productReuseIdentifier forIndexPath:indexPath];
    
    GoodListsModel *goodListsModel = self.productSearchArray[indexPath.item];
    
    NSString *string = [NSString stringWithFormat:@"%@%@",_urlDict[@"m"],goodListsModel.picurl];
    [cell.productImage sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"goodsLoadJGG.jpg"]];
    cell.productImage.contentMode = UIViewContentModeScaleToFill;
    
    cell.productName.text = goodListsModel.title;
    cell.price.text = [NSString stringWithFormat:@"专享价: %@",goodListsModel.huiyuanjia];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
    
}

#pragma mark>>>>>>>>>>>>代理
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    GoodListsModel *goodListsModel = self.productSearchArray[indexPath.item];
    ShopDetailsController *detailsVC = [[ShopDetailsController alloc] init];
    detailsVC.goodsId = goodListsModel.replaceID;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:detailsVC];
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake(WIDTH/2-2, HEIGHT/2.8);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(1,1,1,1);
}


# pragma  mark  UI
- (void)buildCollectionView
{
    [noDrawImage removeFromSuperview];
    [_HistoryView removeFromSuperview];
    
    if (self.productSearchArray.count == 0) {
        //暂无地址(图)
        noDrawImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noSearchProduct"]];
        [self.view addSubview:noDrawImage];
        
        [noDrawImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.centerY.equalTo(self.view.mas_centerY).offset(-HEIGHT/5);
            make.width.mas_equalTo(WIDTH/2);
            make.height.mas_equalTo(HEIGHT/4);
        }];
    }else{
        
        UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
        flowlayout.minimumLineSpacing = 2;
        flowlayout.minimumInteritemSpacing = 0;
        flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        UICollectionView *productSearchView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,WIDTH, HEIGHT-64) collectionViewLayout:flowlayout];
        self.productSearchView = productSearchView;
        self.productSearchView.delegate = self;
        self.productSearchView.dataSource = self;
        productSearchView.backgroundColor = BACKGROUND_COLOR;
        [self.view addSubview:productSearchView];
        
        [self.productSearchView registerClass:[homeCollectionViewCell class] forCellWithReuseIdentifier:productReuseIdentifier];
        
        [self addPullUpdateData];
    }
    
    
}


- (void)buildView
{
    CGRect frame;
    if (WIDTH == 320) {
        frame = CGRectMake(-25, 0, 200, 30);
    } else {
        frame = CGRectMake(0, 0, 200, 30);
    }
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0,WIDTH * 0.7, 30)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = 6;
    view.layer.borderColor = [UIColor colorWithRed:100 / 255.0 green:100 / 255.0 blue:100 / 255.0 alpha:1].CGColor;
    view.layer.borderWidth = 0.2;
    
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:frame];
    //yes首页push no商家push
    _searchBar.placeholder = _goodsStutas ? @"在此输入商品名称":@"在此输入商家名称";
    if (_isBussinessProduct) {
        _searchBar.placeholder = @"在此输入商家产品名称";
    }
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.keyboardType = UIKeyboardAppearanceDefault;
    _searchBar.delegate = self;
    [_searchBar becomeFirstResponder];
    self.navigationItem.titleView = _searchBar;
}

- (NSMutableArray *)histArray
{
    if (!_histArray) {
        _histArray = [[NSMutableArray alloc] init];
    }
    return _histArray;
}


- (NSMutableArray *)productSearchArray {
    if (!_productSearchArray) {
        _productSearchArray = [NSMutableArray array];
    }
    return _productSearchArray;
}

@end
